<template>
  <div class="app-container">
    <!-- 操作按钮 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <!-- 搜索栏 -->
        <el-form :inline="true" :model="searchForm" class="mb-20">
          <el-form-item label="用户名">
            <el-input v-model="searchForm.keyword" placeholder="输入关键词搜索" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="12" class="text-right mb-20" align="right">
        <el-button type="primary" @click="handleAddUser">新增用户</el-button>
      </el-col>
    </el-row>

    <!-- 用户表格 -->
    <el-table :data="userInfoList" border style="width: 100%">
      <el-table-column label="序号" width="80" align="center">
        <template slot-scope="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="nickname" label="昵称" align="center" />
      <el-table-column prop="avatar" label="头像" align="center">
        <template slot-scope="scope">
          <el-avatar :src="scope.row.avatar" size="small" />
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" align="center" />
      <el-table-column prop="phone" label="电话" align="center" />
      <el-table-column prop="sex" label="性别" align="center" />
      <el-table-column label="角色" align="center">
        <template slot-scope="scope">
          {{ formatRole(userList[scope.$index]) }}
        </template>
      </el-table-column>
      <el-table-column label="最后登录时间" width="160" align="center">
        <template slot-scope="scope">
          {{ userList[scope.$index].lastLoginTime }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEditUser(scope.$index)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDeleteUser(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      class="mt-20"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="pageSize"
      :current-page="currentPage"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增/编辑用户弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
      <el-form ref="userForm" :model="userForm" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="头像" prop="avatar">
              <el-upload
                style="border: 1px dashed #d9d9d9;"
                class="avatar-uploader"
                :action="uploadCoverUrl"
                :headers="uploadHeaders"
                :show-file-list="false"
                :on-success="handleCoverSuccess"
                :before-upload="beforeUpload"
              >
                <el-image
                  v-if="userForm.avatar"
                  :src="userForm.avatar"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item v-if="dialogType === 'add'" label="用户名" prop="username">
              <el-input v-model="userForm.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="dialogType === 'add'" label="密码" prop="password">
              <el-input v-model="userForm.password" placeholder="请输入密码" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="userForm.phone" placeholder="请输入电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="role">
              <el-select v-model="userForm.role" placeholder="请选择角色">
                <el-option label="超级管理员" value="ROOT" />
                <el-option label="管理员" value="ADMIN" />
                <el-option label="普通用户" value="USER" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="role">
              <el-select v-model="userForm.sex" placeholder="请选择性别">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getList, deleteUser, saveUserForm } from '@/api/user' // 后期替换为真实接口
import { validEmail } from '@/utils/validate'
import { getToken } from '@/utils/auth' // 自定义验证规则

export default {
  name: 'UserManage',
  data() {
    return {
      uploadHeaders: {
        Authorization: `${getToken()}`
      },
      uploadCoverUrl: '/api/uploadfile/upload',
      userList: [], // 用户列表
      userInfoList: [], // 用户信息列表
      total: 0, // 总记录数
      pageSize: 10, // 每页数量
      currentPage: 1, // 当前页码
      searchForm: {
        keyword: ''
      },
      dialogVisible: false, // 弹窗显示状态
      dialogTitle: '新增用户', // 弹窗标题
      dialogType: 'add', // add/edit
      userForm: {
        userId: null,
        username: '',
        password: '',
        nickname: '',
        email: '',
        phone: '',
        role: '',
        avatar: ''
      },
      rules: {
        username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' }, {
          min: 6,
          message: '密码至少6位',
          trigger: 'blur'
        }],
        nickname: [{ required: true, message: '昵称不能为空', trigger: 'blur' }],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { validator: validEmail, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '电话不能为空', trigger: 'blur' }
        ],
        role: [{ required: true, message: '请选择角色', trigger: 'change' }]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 获取用户列表
    async fetchData() {
      try {
        const res = await getList({
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          ...this.searchForm
        })
        console.log(res)
        this.userInfoList = res.userinfoPage.records
        this.total = res.userinfoPage.total
        this.userList = res.userList
      } catch (error) {
        this.$message.error('获取用户列表失败')
      }
    },
    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        username: '',
        nickname: ''
      }
      this.currentPage = 1
      this.fetchData()
    },
    // 上传封面成功
    handleCoverSuccess(res) {
      console.log(res)
      this.userForm.avatar = res.url
    },
    // 上传前检查文件类型和大小
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isImage) {
        this.$message.error('只能上传图片文件')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB')
      }
      return isImage && isLt2M
    },
    // 新增用户弹窗
    handleAddUser() {
      this.dialogType = 'add'
      this.dialogTitle = '新增用户'
      this.userForm = {
        userId: null,
        username: '',
        password: '',
        nickname: '',
        email: '',
        phone: '',
        role: '',
        sex: '',
        avatar: ''
      }
      this.dialogVisible = true
    },
    // 编辑用户
    handleEditUser(index) {
      const row = this.userInfoList[index]
      this.dialogType = 'edit'
      this.dialogTitle = '编辑用户'
      this.userForm = {
        userId: row.userId,
        username: this.userList[index].username,
        password: this.userList[index].password, // 注意：密码不显示，仅允许修改其他信息
        nickname: row.nickname,
        email: row.email,
        phone: row.phone,
        role: this.userList[index].role,
        sex: row.sex,
        avatar: row.avatar
      }
      this.dialogVisible = true
    },
    // 提交表单（新增/编辑）
    async handleSubmit() {
      if (this.dialogType === 'add') {
        try {
          await saveUserForm(this.userForm)
          this.$message.success('新增成功')
          this.dialogVisible = false
          this.fetchData()
        } catch (error) {
          this.$message.error('新增失败')
        }
      } else {
        try {
          await saveUserForm(this.userForm)
          this.$message.success('更新成功')
          this.dialogVisible = false
          this.fetchData()
        } catch (error) {
          this.$message.error('更新失败')
        }
      }
    },
    // 删除用户
    handleDeleteUser(row) {
      this.$confirm('确定删除该用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          await deleteUser(row.userId)
          this.$message.success('删除成功')
          this.fetchData()
        } catch (error) {
          this.$message.error('删除失败')
        }
      })
    },
    // 分页
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    // 格式化角色
    formatRole(row) {
      console.log(row)
      switch (row.role) {
        case 'ROOT':
          return '超级管理员'
        case 'ADMIN':
          return '管理员'
        case 'USER':
          return '普通用户'
        default:
          return '未知'
      }
    }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.mb-20 {
  margin-bottom: 20px;
}

.mt-20 {
  margin-top: 20px;
}
</style>
